import {
  dsx
} from './datax';
import {
  users
} from './users'
import {
  ds
} from './data'

export const adv = {
  async bind(userOpenid, staffOpenId) {
    if (userOpenid == staffOpenId) return {
      success: false,
      msg: '不能自我绑定'
    }
    const user = await users.getUserByOpenid(userOpenid, {
      bind: true
    })
    if (user.bind) return {
      success: false,
      msg: "已存在绑定"
    }

    const res = await dsx.cloudUpdateWhere('users', {
      _id: user._id
    }, {
      bind: staffOpenId,
      bindTime: new Date().getTime()
    })
    // console.log(res)
    const success = res.errMsg.endsWith(':ok')
    return {
      success,
      msg: success ? "绑定成功" : "绑定失败"
    };
  },

  async calcDeductFee(staff) { // 计算推广佣金. staff: {_id, _openid, deductFee}
    const ordersRes = await this.loadOrders(staff)
    const {
      orders,
      endTime
    } = ordersRes
    let startTime = ordersRes.startTime

    let totalFee = 0
    orders.forEach(anOrder => {
      startTime = (startTime ? Math.min(startTime, anOrder.createTime) : anOrder.createTime) // startTime修正为确切的起始时间
      let goodsMap = {}
      anOrder.goodsSnap.forEach(aSnap => {
        goodsMap[aSnap._id] = aSnap
      })
      anOrder.goodsList.forEach(aGoods => {
        const {
          num,
          price
        } = aGoods
        const deduct = Number(goodsMap[aGoods.spuId].deduct)
        // console.log('deduct', deduct)
        let fee = 0
        if (deduct >= 1) fee = Number(num) * (deduct)
        else if (deduct < 1) fee = Number(num) * Number(price) * (deduct)
        totalFee += fee
      })
    })
    // console.log('total fee', totalFee)

    return {
      fee: totalFee,
      startTime,
      endTime
    }
  },
  async settleDeductFee(staff, feeInfo) { // 结算推广佣金. staff: {_id, _openid, deductFee}, feeInfo: {startTime, endTime, fee}
    if (!feeInfo.startTime || !feeInfo.endTime || feeInfo.startTime > feeInfo.endTime) {
      return {
        success: false,
        msg: '日期区间错误'
      }
    }

    // 去除重复
    const deductFee = (staff.deductFee || [])
    const found = deductFee.find(ele => (ele.start == feeInfo.start && ele.end == feeInfo.end))
    if (found) {
      return {
        success: false,
        msg: '重复结算'
      }
    }

    deductFee.push({
      start: feeInfo.startTime,
      end: feeInfo.endTime,
      fee: feeInfo.fee,
    })
    // console.log('deliveryFee', deliveryFee, staff._id)

    // 更新
    const resUpdate = await dsx.cloudUpdate('users', staff._id, {
      deductFee
    })
    return {
      success: resUpdate.result?.errMsg.endsWith(":ok"),
      msg: resUpdate.result?.errMsg
    }
  },
  async loadOrders(staff) {
    // 绑定的用户
    const userRes = await ds.coll('users')
      .where({
        bind: ds.cmd.eq(staff._openid)
      })
      .get()
    const bindUsers = userRes.data
    const deductFee = staff.deductFee
    // console.log('bind users', bindUsers)

    // 这些用户的订单
    const _ = ds.cmd
    const startTime = this.calcStartTime(deductFee), // 上次结算的终结时间，作为本次结算的起始时间
      endTime = new Date().getTime()
    const userOpenids = bindUsers.map(ele => ele._openid)
    // console.log('user openids', userOpenids)
    // console.log('startTime', startTime)
    const orders = await ds.getAll('orders', {
      _openid: _.in(userOpenids),
      status: '已送达',
      createTime: _.and(startTime ? _.gt(startTime) : {}, _.lte(endTime))
    })
    // console.log('orders', orders)

    return {
      orders,
      startTime,
      endTime
    }
  },
  calcStartTime(deductFee) {
    let start = false;
    (deductFee || []).forEach(obj => {
      start = (start ? Math.max(obj.end, start) : obj.end)
    })

    // console.log('start', start)
    // if (start) {
    //   const date = this.data.date
    //   date.start = start
    //   this.setData({
    //     date
    //   })
    // }
    return start
  },

}